package com.swufe.scoresforapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Adapter;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.swufe.scoresforapp.adapter.RecyclerAdapter;
import com.swufe.scoresforapp.bean.SchoolBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CollectionActivity extends AppCompatActivity {

    @BindView(R.id.collect_layout)
    DrawerLayout mCollectLayout;
    @BindView(R.id.toolbar3)
    Toolbar mToolbar;
    @BindView(R.id.search_view)
    MaterialSearchView mSearchView;
    @Nullable ViewGroup container;
    @Nullable Bundle bundle;

    private TabLayout mTabLayout = null;
    private MyViewPager mViewPager;
    private RecyclerView recyclerView;
    private TabFragment[] mFragments = new TabFragment[3];

    private String[] mTabTitles = new String[3];
    public static Map<Fragment, String> map;
    private List<Integer> position;//用来记录搜索时要显示的Bean
    private Handler handler;
    private FragmentManager manager = getSupportFragmentManager();
   // private Fragment from;
    private LinearLayoutManager mLayoutManager;
    private int pos;

    //private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_collection);

        ButterKnife.bind(this);

        mToolbar.setTitle("我的收藏");
        //设置Toolbar
        setToolbar();


        recyclerView = findViewById(R.id.recycler);
        mTabLayout = findViewById(R.id.tablayout);
        mViewPager = findViewById(R.id.tab_viewPager);
        mViewPager.setScrollable(false);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                pos = position;
                Log.i("posTest",""+pos);
            }

            @Override
            public void onPageSelected(int position) {

                invalidateOptionsMenu();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        initView();
        initSearchListener();
    }
    //字符串检验算法 当source中包含sort中的字段就返回true
    private boolean compareStr(String[] sort,String source){
        int i = 0;
        int length = sort.length;
        double test;
        for(;i<length;i++){
            test= Computeclass.SimilarDegree(sort[i],source);
            if(test>0.2)return true;
        }
        return false;
    }


    private void initSearchListener(){

        mSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {//搜索提交
                   Snackbar.make(findViewById(R.id.collect_layout), "Query:" +query, Snackbar.LENGTH_LONG).show();
                    final String input = query;
                    //from= manager.findFragmentByTag("android:switcher:"+R.id.tab_viewPager+":0");
                handler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        if(msg.what == 8){
                            List<SchoolBean> newSchoolBean = (ArrayList<SchoolBean>)msg.obj;
                            if(input.equals("")){
                                Snackbar.make(findViewById(R.id.collect_layout), "请输入搜索信息" , Snackbar.LENGTH_LONG).show();
                                newSchoolBean = mFragments[pos].getmSchoolBeans();
                            }else if(newSchoolBean.size()==0){
                                newSchoolBean = mFragments[pos].getmSchoolBeans();
                                Snackbar.make(findViewById(R.id.collect_layout), "无相关信息", Snackbar.LENGTH_LONG).show();
                            }else
                            {
                            }
                            //Log.i("infoCheck",newSchoolBean.get(0).Schoolname);
                            RecyclerAdapter adapter = new RecyclerAdapter(mFragments[pos].getContext(),newSchoolBean,mTabTitles[pos]);
                            LayoutInflater inflater = (LayoutInflater)mFragments[pos].getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
                            recyclerView = (RecyclerView)findViewById(R.id.recycler);
                            setmAdapter(adapter,newSchoolBean);
                            adapter.notifyDataSetChanged();
                            removeCallbacksAndMessages(null);


                        }
                        super.handleMessage(msg);
                    }
                };
                new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int i=0;
                            String b = new String("");
                            String []sort = input.split("\\s+");
                            int length = mFragments[pos].getmSchoolBeans().size();
                            position = new ArrayList<>();
                            String title = new String();
                            title = mTabTitles[pos];
                            Log.i("fromtext",title);
                            for (i=0;i<length;i++){
                                if(title.equals("学校")){
                                    b = mFragments[pos].getmSchoolBeans().get(i).Schoolname;
                                    String c = mFragments[pos].getmSchoolBeans().get(i).major;
                                    //Log.i("majortest",b);
                                   // Log.i("schooltest",c);
                                }else if(title.equals("专业"))
                                {
                                    b = mFragments[pos].getmSchoolBeans().get(i).major;
                                }else if(title.equals("对比")){
                                    b = mFragments[pos].getmSchoolBeans().get(i).school1;
                                }
                                b.replace("大学","");
                                if(compareStr(sort,b)) {
                                    position.add(i);
                                    //Log.i("infoCheck",b);
                                }
                            }
                            List<SchoolBean> newSchoolBean = new ArrayList<>();
                            for(i=0;i<position.size();i++){
                                newSchoolBean.add(mFragments[pos].getmSchoolBeans().get(position.get(i)));

                            }
                            Message msg = handler.obtainMessage(8);
                            msg.obj = newSchoolBean;
                            handler.sendMessage(msg);
                        }
                    }).start();



                return false;
            }

            //设置Adapter
            public void setmAdapter(final RecyclerAdapter mAdapter,final List<SchoolBean> mSchoolBeans){
                mAdapter.setOnDelListener(new RecyclerAdapter.onSwipeListener() {
                    @Override
                    public void onDel(int pos) {
                        if (pos >= 0 && pos < mSchoolBeans.size()) {
                            Toast.makeText(mFragments[pos].getActivity(), "删除:" + pos, Toast.LENGTH_SHORT).show();
                            mSchoolBeans.remove(pos);
                            mAdapter.notifyItemRemoved(pos);//推荐用这个
                            //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                            //且如果想让侧滑菜单同时关闭，需要同时调用 ((SwipeMenuLayout) holder.itemView).quickClose();
                            //mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onTop(int pos) {
                        if (pos > 0 && pos < mSchoolBeans.size()) {
                            SchoolBean swipeBean = mSchoolBeans.get(pos);
                            mSchoolBeans.remove(swipeBean);
                            mAdapter.notifyItemInserted(0);
                            mSchoolBeans.add(0, swipeBean);
                            mAdapter.notifyItemRemoved(pos + 1);
                            if (mLayoutManager.findFirstVisibleItemPosition() == 0) {
                                recyclerView.scrollToPosition(0);
                            }
                            //notifyItemRangeChanged(0,holder.getAdapterPosition()+1);
                        }
                    }

                    @Override
                    public void onAdd(int pos, ImageView v) {

                    }
                });
                recyclerView.setAdapter(mAdapter);
                mLayoutManager = new LinearLayoutManager(mFragments[pos].getActivity());
                mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                recyclerView.setLayoutManager(mLayoutManager);
                //流式
                //recyclerView.setLayoutManager(mLayoutManager = new GridLayoutManager(this.getContext(), 2));

                // 可以用在：当点击外部空白处时，关闭正在展开的侧滑菜单。我个人觉得意义不大，
                recyclerView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            SwipeMenuLayout viewCache = SwipeMenuLayout.getViewCache();
                            if (null != viewCache) {
                                viewCache.smoothClose();
                            }
                        }
                        return false;
                    }
                });
                mAdapter.setOnItemClickListener(new RecyclerAdapter.onItemClickListener() {
                    @Override
                    public void onItemClick(int tag, View view, int position) {
                        Toast.makeText(mFragments[pos].getContext(), "点击", Toast.LENGTH_SHORT).show();
                        Intent intent;
                        String title = mTabTitles[pos];
                        if(title.equals("学校")) {
                            intent = new Intent(mFragments[pos].getContext(), ScrollingSchoolActivity.class);
                            intent.setClass(mFragments[pos].getContext(), ScrollingSchoolActivity.class);
                        }else if(title.equals("专业")){
                            Log.i("try","");
                            intent = new Intent(mFragments[pos].getContext(), ScrollingMajorActivity.class);
                            intent.setClass(mFragments[pos].getContext(), ScrollingMajorActivity.class);
                        }else{

                            intent = new Intent(mFragments[pos].getContext(), CompareActivity.class);
                            intent.setClass(mFragments[pos].getContext(), CompareActivity.class);
                        }
                        //
                        //intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("information", new Gson().toJson(mSchoolBeans.get(position)));
                        mFragments[pos].getContext().startActivity(intent);
                    }

                    @Override
                    public void onItemLongClick(int tag, View view, int position) {
                        Toast.makeText(mFragments[pos].getContext(), "长按", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //刷新页面
            /*public void refresh(final List<SchoolBean> newSchoolBeans){
                @Nullable ViewGroup container;
                @Nullable Bundle bundle;
                LayoutInflater inflater =
                final LinearLayoutManager mLayoutManager;
                final RecyclerView recyclerView = inflater.inflate(R.layout.fragment_tab, container, false);;
                final View rootView = rootView.findViewById(R.id.recycler);
                final RecyclerAdapter  mAdapter = new RecyclerAdapter(from.getContext(), newSchoolBeans,CollectionActivity.map.get(from));
                mAdapter.setOnDelListener(new RecyclerAdapter.onSwipeListener() {
                    @Override
                    public void onDel(int pos) {
                        if (pos >= 0 && pos < newSchoolBeans.size()) {
                            Toast.makeText(from.getActivity(), "删除:" + pos, Toast.LENGTH_SHORT).show();
                            newSchoolBeans.remove(pos);
                            mAdapter.notifyItemRemoved(pos);//推荐用这个
                            //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                            //且如果想让侧滑菜单同时关闭，需要同时调用 ((SwipeMenuLayout) holder.itemView).quickClose();
                            //mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onTop(int pos) {
                        if (pos > 0 && pos < newSchoolBeans.size()) {
                            SchoolBean swipeBean = newSchoolBeans.get(pos);
                            newSchoolBeans.remove(swipeBean);
                            mAdapter.notifyItemInserted(0);
                            newSchoolBeans.add(0, swipeBean);
                            mAdapter.notifyItemRemoved(pos + 1);
                            if (mLayoutManager.findFirstVisibleItemPosition() == 0) {
                                recyclerView.scrollToPosition(0);
                            }
                            //notifyItemRangeChanged(0,holder.getAdapterPosition()+1);
                        }
                    }
                });
                recyclerView.setAdapter(mAdapter);
                mLayoutManager = new LinearLayoutManager(from.getActivity());
                mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                recyclerView.setLayoutManager(mLayoutManager);
                //流式
                //recyclerView.setLayoutManager(mLayoutManager = new GridLayoutManager(this.getContext(), 2));

                // 可以用在：当点击外部空白处时，关闭正在展开的侧滑菜单。我个人觉得意义不大，
                recyclerView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            SwipeMenuLayout viewCache = SwipeMenuLayout.getViewCache();
                            if (null != viewCache) {
                                viewCache.smoothClose();
                            }
                        }
                        return false;
                    }
                });

            }*/



            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {

            }

            @Override
            public void onSearchViewClosed() {

            }
        });
        mSearchView.setVoiceSearch(false);
        mSearchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
        mSearchView.setCursorDrawable(R.drawable.custom_cursor);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK){
            ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if(matches != null && matches.size() > 0){
                String searchWrd = matches.get(0);
                if(!TextUtils.isEmpty(searchWrd)){
                    mSearchView.setQuery(searchWrd, false);
                }
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if(mSearchView.isSearchOpen()){
            mSearchView.closeSearch();
        }else{
            super.onBackPressed();
        }
    }

    private void initView(){

        mTabTitles[0] = getResources().getString(R.string.school);
        mTabTitles[1] = getResources().getString(R.string.major);
        mTabTitles[2] = getResources().getString(R.string.compare);

        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mFragments[0] = TabFragment.newInstance();
        mFragments[1] = TabFragment.newInstance();
        mFragments[2] = TabFragment.newInstance();
        map = new HashMap<Fragment, String>();
        PagerAdapter pagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(pagerAdapter);
        //将ViewPager和TabLayout绑定
        mTabLayout.setupWithViewPager(mViewPager);
        map.put(mFragments[0],mTabTitles[0]);
        map.put(mFragments[1],mTabTitles[1]);
        map.put(mFragments[2],mTabTitles[2]);
    }

    final class MyViewPagerAdapter extends FragmentPagerAdapter {
        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            return mFragments[position];
        }
       /*private XXXFragment mCurrentFragment;
        private List<XXX> mList;

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            mCurrentFragment = (TabFragment) object;
            super.setPrimaryItem(container, position, object);
        }
        public TabFragment getCurrentFragment() {
            return mCurrentFragment;
        }
*/
        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            return super.instantiateItem(container, position);
        }

        @Override
        public int getCount() {
            return mFragments.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {

            return mTabTitles[position];

        }
    }

    private void setToolbar() {
        setSupportActionBar(mToolbar);
        // 显示Home的图标
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

   /* private void setDrawerToggle() {
        mToggle=new ActionBarDrawerToggle(this,mCollectLayout,mToolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);
        mCollectLayout.addDrawerListener(mToggle);
        //同步DrawerLayout的状态
        mToggle.syncState();
    }
*/
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.menu_collect, menu);

       MenuItem search = menu.findItem(R.id.item_search);
       mSearchView.setMenuItem(search);

       return true;
   }
    /*@Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item1 = menu.findItem(R.id.item_search);
        MenuItem item2 = menu.findItem(R.id.item_manage);
        switch (mViewPager.getCurrentItem()) {
            case 0:
                //mNavigationView.getMenu().getItem(0).setChecked(true);
                item1.setVisible(true);
                item2.setVisible(false);
                item3.setVisible(false);
                item4.setVisible(false);
                break;
            case 1:
                mToolbar.setTitle(R.string.school);
                setToolbar();
                setDrawerToggle();
                //mNavigationView.getMenu().getItem(0).setCheckable(false);
                item1.setVisible(false);
                item2.setVisible(true);
                item3.setVisible(false);
                item4.setVisible(false);
                break;
        }
        return super.onPrepareOptionsMenu(menu);
    }*/

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_search:
                Toast.makeText(CollectionActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                break;
           /* case R.id.item_manage:
                Toast.makeText(CollectionActivity.this, "管理", Toast.LENGTH_SHORT).show();
                break;*/
            /*case android.R.id.home:
                this.finish();
                return true;*/
        }
        return super.onOptionsItemSelected(item);
    }

}
